#include "fpsCounter.h"


fpsCounter::fpsCounter() : smoothingWindow(333) {	
	
	//Register object to catch the relevant oF events
	ofAddListener(ofEvents.mouseDragged, this, &fpsCounter::mouseDragged);
	ofAddListener(ofEvents.mousePressed, this, &fpsCounter::mousePressed);
	ofAddListener(ofEvents.mouseReleased, this, &fpsCounter::mouseReleased);
	ofAddListener(ofEvents.draw, this, &fpsCounter::draw);

	defaultFont.loadFont("fonts/consola.ttf", 11);
	sprintf(fpsString, "Frame rate: ?");

	// Initial frame location
	frame.x = 40;
	frame.y = 40;

	//Init mouse state
	dragging = false;

	//Init counters
	lastFrameTotal = ofGetFrameNum();
	lastQueryTime = ofGetElapsedTimeMillis();
}


fpsCounter::~fpsCounter()
{
	ofRemoveListener(ofEvents.mouseDragged, this, &fpsCounter::mouseDragged);
	ofRemoveListener(ofEvents.mousePressed, this, &fpsCounter::mousePressed);
	ofRemoveListener(ofEvents.mouseReleased, this, &fpsCounter::mouseReleased);
	ofRemoveListener(ofEvents.draw, this, &fpsCounter::draw);
}


void fpsCounter::draw( ofEventArgs& arg )
{
	updateFpsString();
	drawFPS();
}


void fpsCounter::drawFPS()
{
	glPushMatrix();
	glTranslatef(0,0,0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, ofGetWidth(), ofGetHeight(), 0, 0, -ofGetHeight());

	//Frame size
	ofRectangle strBounds = defaultFont.getStringBoundingBox(fpsString, 0, 0);
	frame.width =  strBounds.width + 5 - fmod(strBounds.width, 5);
	frame.height = strBounds.height;

	//Draw text box
	ofEnableAlphaBlending();
	ofFill();
	ofSetColor(255,255,255,220);
	ofSetLineWidth(1);
	ofRect(frame.x, frame.y, frame.width, frame.height);
	ofDisableAlphaBlending();
	ofSetColor(255,0,0,255);
	ofNoFill();
	ofRect(frame.x-1, frame.y, frame.width+1, frame.height+1);

	//Print string	
	ofSetColor(0x000000);
	defaultFont.drawString(fpsString, frame.x, frame.y + frame.height*0.68);
	
	glPopMatrix();
}


void fpsCounter::mouseDragged(ofMouseEventArgs& arg)
{
	if(dragging){				
		frame.x = arg.x-dragOffsetX;
		frame.y = arg.y-dragOffsetY;
	}
}


void fpsCounter::mousePressed(ofMouseEventArgs& arg)
{
	if(arg.button == 0){
		if(frame.inside(arg.x, arg.y)){
			dragging = true;
			dragOffsetX = arg.x-frame.x;
			dragOffsetY = arg.y-frame.y;
		}
	}
}


void fpsCounter::mouseReleased(ofMouseEventArgs& arg)
{
	if(arg.button == 0){
		dragging = false;
	}
}


void fpsCounter::updateFpsString()
{
	int timeDelta = ofGetElapsedTimeMillis() - lastQueryTime;

	if(timeDelta >= smoothingWindow){
		int frameDelta = ofGetFrameNum() - lastFrameTotal;
		float fps = 1000 / (timeDelta / (float)frameDelta);
		sprintf(fpsString, "Frame rate: %.1f", fps);
		lastFrameTotal = ofGetFrameNum();
		lastQueryTime = ofGetElapsedTimeMillis();
	}
}






